<template>
  <el-main class="category-main-content">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="分类名称">
          <el-input v-model="searchForm.name" placeholder="请输入分类名称" clearable />
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 分类列表 -->
    <el-card class="category-list-card">
      <el-table :data="categoryList" stripe border highlight-current-row :empty-text="loading ? '加载中...' : '暂无数据'">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="分类名称" min-width="150" />
        <el-table-column prop="parentName" label="父级分类" min-width="120" />
        <el-table-column prop="sort" label="排序号" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="160" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button type="primary" size="small" @click="editCategory(scope.row.id)">
              <el-icon>
                <Edit />
              </el-icon>
              <span>编辑</span>
            </el-button>
            <el-button type="danger" size="small" @click="deleteCategory(scope.row.id, scope.row.name)">
              <el-icon>
                <Delete />
              </el-icon>
              <span>删除</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total" />
    </el-card>
  </el-main>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { Plus, Folder, Edit, Delete } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';

const router = useRouter();

// 搜索表单数据
const searchForm = reactive({
  name: '',
  status: ''
});

// 分类列表数据
const categoryList = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 获取分类列表
const getCategoryList = async () => {
  loading.value = true;
  try {
    const response = await axios.get('/categories/', {
      params: {
        name: searchForm.name,
        status: searchForm.status,
        page: currentPage.value,
        page_size: pageSize.value
      }
    });

    if (response.data.code === 200) {
      categoryList.value = response.data.data.list;
      total.value = response.data.data.total;
    } else {
      ElMessage.error(response.data.msg);
    }
  } catch (error) {
    ElMessage.error('获取分类列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 搜索分类
const search = () => {
  currentPage.value = 1; // 重置为第一页
  getCategoryList();
};

// 重置搜索条件
const resetSearch = () => {
  searchForm.name = '';
  searchForm.status = '';
  currentPage.value = 1;
  getCategoryList();
};

// 分页相关
const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize;
  getCategoryList();
};

const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage;
  getCategoryList();
};

// 编辑分类
const editCategory = (id: number) => {
  router.push({ name: 'EditCategory', params: { id } });
};

// 删除分类
const deleteCategory = (id: number, name: string) => {
  ElMessageBox.confirm(
    `确定要删除分类【${name}】吗？删除后将无法恢复。`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await axios.delete(`/categories/${id}/`);
      if (response.data.code === 200) {
        ElMessage.success('分类删除成功');
        getCategoryList(); // 刷新列表
      } else {
        ElMessage.error(response.data.msg);
      }
    } catch (error) {
      ElMessage.error('删除失败，请稍后重试');
    }
  }).catch(() => {
    // 用户取消操作
  });
};

// 页面加载时初始化
onMounted(() => {
  getCategoryList();
});
</script>
<style scoped></style>